package com.example.langchanin4jdemo1.controller;

import dev.langchain4j.community.model.dashscope.QwenChatModel;
import dev.langchain4j.community.model.dashscope.QwenEmbeddingModel;
import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.embedding.EmbeddingModel;
import dev.langchain4j.model.output.Response;
import dev.langchain4j.rag.content.Content;
import dev.langchain4j.rag.content.retriever.ContentRetriever;
import dev.langchain4j.rag.content.retriever.EmbeddingStoreContentRetriever;
import dev.langchain4j.rag.query.Query;
import dev.langchain4j.store.embedding.redis.RedisEmbeddingStore;
import org.springframework.ai.document.DocumentReader;
import org.springframework.ai.reader.tika.TikaDocumentReader;
import org.springframework.context.annotation.Bean;

import java.util.ArrayList;
import java.util.List;

/**
 * 此方法有问题
 */
public class RagSearchDemo1 {
    public static void main(String[] args) throws Exception {

        String question = "ECS实例怎么开具发票";
        //文本向量化村粗
        EmbeddingModel embeddingModel = QwenEmbeddingModel
                .builder()
                .apiKey("sk-875dd6ef14244431acdc7ccb974f5bfe")
                .modelName("text-embedding-v2")
                .build();

        RedisEmbeddingStore embeddingStore = RedisEmbeddingStore.builder()
                .host("127.0.0.1")
                .port(6379)
                .dimension(1536) //维度，需要与计算结果保持⼀致。如果使⽤其他的模型，可能会有不同的结果。
                .indexName("service_rag")
                .build();

        ContentRetriever contentRetriever = EmbeddingStoreContentRetriever.builder()
                .embeddingStore(embeddingStore) //向量存储模型
                .embeddingModel(embeddingModel) //向量模型
                .maxResults(5) // 最相似的5个结果
                .minScore(0.8) // 只找相似度在0.8以上的内容
                .build();

        ChatLanguageModel model = QwenChatModel.builder()
                .apiKey("sk-875dd6ef14244431acdc7ccb974f5bfe")
                .modelName("qwen-plus")
                .build();
        // 定义用户消息
        UserMessage userMessage = new UserMessage(question);

        // 创建查询

        Query query = new Query(question);
        List<Content> contentList = contentRetriever.retrieve(query);
        for (Content content : contentList) {
            System.out.println(content+"检索");
        }

        List<ChatMessage> context = new ArrayList<>();
        context.add(userMessage);
        for (Content content : contentList) {
            context.add(new UserMessage(content.textSegment().text()));
        }

        Response<AiMessage> generate = model.generate(context);
        System.out.println(generate.content().text());
    }

}
